<?php
namespace app\common\controller;
use think\Loader;
use think\Controller;
use think\Db;
use app\common\model\Prt;
use app\common\model\CorePayLog;

/**
* 后台公用基础控制器
* @author taigu
* @version 2017-9-22
*/
class PaylogBaseController extends Controller {
	//打印付款日志
	function print_log($out_trade_no,$receiveAmount){
		//预付款日志
		$paylog=db("log_paylog")->where('order_sn', $out_trade_no)->find();
		if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			//echo '数据异常';exit;
		}
		//付款用户
		$user_info = db('info_user')->where('id',$paylog['uid'])->find();
		//收款商家
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		//支付类型
		$order_type = $paylog['order_type'];
		//实付金额
		$price	 = $paylog['balance'];
		//分销设置
		$config=get_config("fx_config");	
		//应付金额				
		$pay_money =	$paylog['origin_price'];	
		if($order_type == 1){	//订单
			$this->do_order($user_info,$paylog,$price);
		}else if($order_type == 2 ){	//扫码支付
			$this->agent_pay_qrcode($paylog,$price,$pay_money,$agent_info,$user_info,$out_trade_no);
			//商户，会员关系表
			$this->user_relevance_agent($user_info['id'],$agent_info['id'],$price);
		}else if($order_type == 3){	//用户充值
			
		}else if($order_type == 4){	//广告充值
			$this->agent_pay_ads($paylog,$agent_info,$config);
		}else if($order_type == 5){	//商家鼓励金充值
			$this->agent_pay_score($paylog,$agent_info);
		}else if($order_type == 6){ //二维码收银
			$this->agent_sy_pay_qrcode($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no);
			//商户，会员关系表
			$this->user_relevance_agent($user_info['id'],$agent_info['id'],$price);
		}else if($order_type == 7){	//单商品
			$this->goods_qrcode_pay($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no);
			//商户，会员关系表
			$this->user_relevance_agent($user_info['id'],$agent_info['id'],$price);
		}else if($order_type == 8){	//用户鼓励金充值
			$this->do_charge($config,$paylog,$user_info,$price);//上级分佣
		}else if($order_type == 9){	//oem鼓励金充值
			$this->oem_pay_score($paylog);
		}else if($order_type == 10){	//商家申请开店
			$this->store_open($paylog,$config);
		}
	}
	
	//付款成功
	function add_corepaylog($paylog){
		$result = db('log_paylog')->where('id', $paylog['id'])->find();
		if($result){
			$corepaylog=new CorePayLog();
			unset($paylog['id']);
			$res=$corepaylog->allowField(true)->save($paylog);
		}else{
			$res= 0;
		}
		
		return $res;
	}	
	/**
	 * 用户资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $operator 加减符号
	 * $message	资金变化详情
	 */
	function user_money_log($u_id,$agent_id,$order_type,$balance,$message){
		$user_info = db('info_user')->where('id',$u_id)->find();
		
		//累计消费次数
		$total_nums = $user_info['total_nums']+1;
		//累计消费金额
		$total_balance = bcadd($user_info['total_balance'], $balance, 2);
		
		Db::table('info_user')
			->where('id', $user_info['id'])
			->update(['total_balance' => $total_balance,'total_nums'=>$total_nums]);
		
		$data = array(
			'u_id'		 	=> $user_info['id'],
			'order_type' 	=> $order_type,
			'balance' 	 	=> $balance,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);
		$result = db('log_user_charge')->insert($data);
		
		return $result;
	}
	
	/**
	 * 用户鼓励金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $balance	金额变化值
	 * $operator 加减符号
	 * $message	变化详情
	 */
	
	function user_score_log($u_id,$order_type,$balance,$message){
		$data = array(
			'u_id'		 =>$u_id,
			'order_type' => $order_type,
			'balance' 	 => $balance,
			'message' 	 => $message,
		    "add_time"	 => now_time()
		);
		return db('log_user_score')->insert($data);
		
	}
	
	/**
	 * 用户佣金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $balance 变化金额
	 * $operator 加减符号
	 */
	function user_commission_log($user_id,$order_sn,$order_type,$balance,$message,$pay_type){
		$data = array(
			'u_id'		 => $user_id,
			'order_sn' 	 => $order_sn,
			'order_type' => $order_type,
			'balance' 	 => $balance,
			'message' 	 => $message,
		    'pay_type' 	 => $pay_type,
		    "add_time"	 => now_time()
		);
		return db('log_user_commission')->insert($data);
	}
	
	
	/**
	 * 商家资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $message	资金变化详情
	 * $operator 加减符号
	 */
	function agent_money_log($paylog,$order_type,$balance,$message){
		
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		
		$data = array(
			'agent_id'		=> $agent_info['id'],
			'chain_id' 	 	=> $paylog['chain_id'],
			'clerk_id' 		=> $paylog['clerk_id'],
			'order_sn' 	 	=> $paylog['order_sn'],
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    'pay_type' 	 	=> $paylog['pay_type'],
		    'status_tinyint'=> 1,
		    'oem_id' 	 	=> $agent_info['oem_id'],
		    'agency_id' 	=> $agent_info['agency_id1'],
		    'city_id' 	 	=> $agent_info['agency_id2'],
		    'salesman_id' 	=> $agent_info['salesman_id'],
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_charge')->insert($data);
	}
	
	/**
	 * 商家鼓励金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $operator 加减符号
	 */
	function agent_score_log($agent_id,$order_type,$balance,$message,$chain_id=0,$clerk_id=0){
		$data = array(
			'agent_id'		=> $agent_id,
			'chain_id' 	 	=> $chain_id,
			'clerk_id' 		=> $clerk_id,
			'balance'		=> $balance,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_score')->insert($data);
	}
	
	/**
	 * 商家佣金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $operator 加减符号
	 */
	function agent_commission_log($agent_id,$order_sn,$order_type,$balance,$message){
		$data = array(
			'agent_id'		=> $agent_id,
			'order_sn'		=> $order_sn,
			'balance'		=> $balance,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_commission')->insert($data);
	}
	
	/**
	 * 商家提前分佣记录
	 */
	function ahead_agent_score_log($paylog,$balance,$message){
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		
		$data = array(
			'agent_id'		=> $agent_info['id'],
			'chain_id' 	 	=> 0,
			'clerk_id' 		=> 0,
			'order_sn' 	 	=> $paylog['order_sn'],
			'order_type' 	=> 8,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    'operator' 	 	=> 0,
		    'pay_type' 	 	=> $paylog['pay_type'],
		    'status_tinyint'=> 0,
		    'oem_id' 	 	=> $agent_info['oem_id'],
		    'agency_id' 	=> $agent_info['agency_id1'],
		    'city_id' 	 	=> $agent_info['agency_id2'],
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_score')->insert($data);
	}
	/**
	 * OEM资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $balance 变化金额
	 * $operator 加减符号
	 */
	function oem_money_log($oem_id,$order_type,$balance,$message){
		
		$data = array(
			'order_type' 	=> $order_type,
			'balance' 	 	=> $balance,
			'oem_id'		=> $oem_id,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);
		
		return db('log_oem_charge')->insert($data);
	}
	/**
	 * OEM鼓励金变化日志
	 */
	function oem_score_log($oem_id,$order_type,$balance,$message){		
			$data['oem_id'] = $oem_id;
			$data['order_type'] = $order_type;
			$data['balance'] = $balance;
			$data['message'] = $message;
			$data['add_time'] = now_time();
		return db('log_oem_score')->insert($data);
	}
    
	/**
	 * OEM佣金变化日志
	 */
	function oem_commission_log($oem_id,$order_type,$balance,$message){		
			$data['oem_id'] = $oem_id;
			$data['order_type'] = $order_type;
			$data['balance'] = $balance;
			$data['message'] = $message;
			$data['add_time'] = now_time();
		return db('log_oem_commission')->insert($data);
	}
	//订单
	function do_order($user_info,$paylog,$price){
		
		$score_commission 			= 0;
		$member_score_commission	= 0;
		$agent_score_commission		= 0;
		$payment_type				= 0;
		$rate_commission			= 0;
		
		$order=db("agent_syorder")->where('sn',$paylog['order_sn'])->find();
		if(!$order){
			echo '下单失败';
		}
		//获取商户信息
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		//检查是否开启鼓励金营销
		if($agent_info['is_score'] == 1){
			$result = true;
			Db::startTrans();
			if($order['need_score'] && $order['need_score']>0){
				//会员鼓励金记录
				$res1 = $this->user_score_log($order['user_id'],1,-$order['need_score'],'订单抵扣鼓励金');
				if(!$res1)$result = false;
				//更新会员鼓励金
				$res2 = db('info_user')->where("id",$order['user_id'])->setDec("score",$order['need_score']);
				if(!$res2)$result = false;
				//商家鼓励金记录
				$this->agent_score_log($order['agent_id'],1,$order['need_score'],'用户下单抵扣鼓励金',$order['chain_id']);
				//更新商家鼓励金
				$res21 = db('info_agent')->where("id",$order['agent_id'])->setInc("score",$order['need_score']);
				if(!$res21)$result = false;
				
				//更新商家，用户鼓励金变化情况(便于统计)
				$score_commission 			= -$order['need_score'];
				$member_score_commission	= -$order['need_score'];
				$agent_score_commission		= $order['need_score'];
				$payment_type 				= 2;
				
			}else{
				if($order['give_score'] >0){
					//会员鼓励金记录
					$this->user_score_log($order['user_id'],1,$order['give_score'],'下单奖励鼓励金');
					//更新会员鼓励金
					$res3 = db('info_user')->where("id",$order['user_id'])->setInc("score",$order['give_score']);
					if(!$res3)$result = false;
					//商家鼓励金记录
					$this->agent_score_log($order['agent_id'],1,-$order['give_score'],'用户下单赠送鼓励金',$order['chain_id']);
					//更新商家鼓励金
					$res31 = db('info_agent')->where("id",$order['agent_id'])->setDec("score",$order['give_score']);
					if(!$res31)$result = false;
					
					//更新商家，用户鼓励金变化情况(便于统计)
					$score_commission 			= $order['give_score'];
					$member_score_commission	= $order['give_score'];
					$agent_score_commission		= -$order['give_score'];
					$payment_type 				= 1;
				}
			}
		}
		
		//费率分佣
		$res5 = $this->feel_commission($paylog);
		if(!$res5)$result = false;
		
		//广告分佣
		if(config('open_sq') == 1 && $agent_info['is_union'] == 1){
			$rest11 = $this->ads_commission($paylog,$agent_info,$user_info);
			if(!$rest11) $result = false;
		}
		
		//oem佣金费率
		$oem_feel = 0.001;
		//计算oem费率佣金
		$rate_commission 		= bcmul($paylog['balance'], $oem_feel, 4);
		
		//更新订单信息 
		$update['score']  			= $score_commission;
		$update['member_score']  	= $member_score_commission;
		$update['agent_score']  	= $agent_score_commission;
		$update['payment_type'] 	= $payment_type;
		$update['rate_commission']  = $rate_commission;
		$update['state']  			= 2;
		$update['pay_time']  		= now_time();
		
		//更新订单信息 
		$rest12 = db('log_paylog')
					->where('order_sn',$paylog['order_sn'])
					->update($update);
		if(!$rest12) $result = false;
		
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
			//发送用户下单通知
			if($user_info&&$user_info['openid']){
				$remark="下单成功通知";
				if($paylog_info["member_score"]>0){
					$remark.=",鼓励金账号增加".$cut_paylog["member_score"];
				}elseif($paylog_info["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$cut_paylog['member_score'];
				}
				$goods_name="消费";
				$goods=db("agent_goods")->field("goods_name")->find($paylog_info['goods_id']);
				if($goods){
					$goods_name=$goods['goods_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$goods,
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>'到店消费',
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>$paylog_info['pay_time'],
	                "color"=>"#173177"
	            ),
	             "keyword5"=> array(
	                "value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    		sendMessage($user_info['openid'],config("tempids.order"),$data,"index/member/orders.html");	
			}
		}
		//app收款提醒
		push_msg($paylog_info['agent_id'],$paylog_info['balance']);
	}
	
	//鼓励金充值
	function do_charge($config,$paylog,$user_info,$price){
			$is_fx=$user_info['is_fx'];
			$cz_score=$price*5;//鼓励金充值1：5
			$sql_user=" update info_user set score=score+$cz_score, total_nums=total_nums+1,total_balance=total_balance+$price";
			if($is_fx!=1&&$price>=config("limit_money")){//判断用户是否具有分享资格
				$sql_user.=",is_fx=1";
			}
			$sql_user.=" where id=".$user_info['id'];
			$result = true;
			Db::startTrans();
			
			//增加推荐会员鼓励金分佣
			$this->user_score_log($user_info['id'],7,$cz_score,'鼓励金充值'.$price.'￥');
			$res1=DB::execute($sql_user);
			if(!$res1) $result =false;
			$up['member_score']=$price*5;
			//用户上级分佣
			$mobile=$user_info['mobile'];
			$this->user_score_log($user_info['level'],10,$price*$config['tj_user']/100,'下级会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
			$cut_price = $price*$config['tj_user']/100;
			$res2=db('info_user')->where("id",$user_info['level'])->setInc("score",$cut_price);
			if(!$res2) $result =false;
			//上级用户
			$up['level1']=$user_info['level'];
			$up['level1_commisssion']=$cut_price;
				
			if($user_info['tj_pt']&&$price*$config['tj_pt']/100){//如果存在推荐合伙人分佣
				$tj_pt=db('info_user')->find($user_info['tj_pt']);
				if($tj_pt&&$tj_pt['is_pt']==1){//判断合伙人状态
					$agent_yj=$price*$config['tj_agent']/100;
					$res3=$this->user_score_log($user_info['tj_pt'],11,$price*$config['tj_pt']/100,'合伙人下级会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
					if(!$res3) $result =false;
					
					$up['pt_id']=$user_info['tj_pt'];
					$up['pt_commission']=$price*$config['tj_pt']/100;
					$res20 = db('info_user')->where("id",$user_info['tj_pt'])->setInc("score",$price*$config['tj_pt']/100);
					if(!$res20) $result =false;
				}else{
					$agent_yj=$price*$config['tj_agent']/100+$price*$config['tj_pt']/100;
				}
			}else{//不存在合伙人的分佣归商家
				$agent_yj=$price*$config['tj_agent']/100+$price*$config['tj_pt']/100;
			}
			$up['agent_score']=$agent_yj;
			//增加推荐商家鼓励金分佣
			if($user_info['tj_agent']){
				$this->agent_score_log($user_info['tj_agent'],9,$agent_yj,'会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
				$res4=db('info_agent')->where("id",$user_info['tj_agent'])->setInc("score",$agent_yj);
				$up['tj_agent_id']=$user_info['tj_agent'];
				$up['tj_agent_commission']=$agent_yj;
				if(!$res4) $result =false;
			}
			if($config['tj_city']){
				$this->oem_score_log($user_info['agency_id2'],7,$price*$config['tj_city']/100,'会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
				$res5=db('info_oem')->where("id",$user_info['agency_id2'])->setInc("score",$price*$config['tj_city']/100);
				$up['agency_id2']=$user_info['agency_id2'];
				$up['agency_id2_commission']=$price*$config['tj_city']/100;
				if(!$res5) $result =false;
			}
			if($config['tj_province']){
				$this->oem_score_log($user_info['agency_id1'],7,$price*$config['tj_province']/100,'会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
				$res6=db('info_oem')->where("id",$user_info['agency_id1'])->setInc("score",$price*$config['tj_province']/100);
				$up['agency_id1']=$user_info['agency_id1'];
				$up['agency_id1_commission']=$price*$config['tj_province']/100;
				if(!$res6) $result =false;
			}
			if($config['tj_oem']){
				$this->oem_score_log(1,7,$price*$config['tj_oem']/100,'会员'.$mobile.'充值'.$price.'￥鼓励金分佣');
				$res7=db('info_oem')->where("id",1)->setInc("score",$price*$config['tj_oem']/100);
				$up['oem_id']=$user_info['oem_id'];
				$up['oem_commission']=$price*$config['tj_oem']/100;
				if(!$res7) $result =false;
			}
			//获取总账号信息
			$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
			//计算当前总账号鼓励金
			$scores = $sys_tongji['scores'] + $cz_score;
			//计算当前总账号充值
			$balances = $sys_tongji['balances'] + $price;
			//更新总账号信息
			$rest10 = Db::table('sys_tongji')->where('id', 1)->update(['scores' => $scores,'balances'=>$balances]);
			if(!$rest10) $result =false;
			
			
			$up['state']			=2;
			$up['pay_time']			=now_time();
			//更新订单信息 
			$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update($up);
			if(!$rest12) $result =false;
				
			if($result){
				Db::commit();
			}else{
				Db::rollback();
			}
			
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
			if($user_info&&$user_info['openid']){
				$data=array(
			 	"first" => array(
	                "value"=>"充值成功，请及时查看！",
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance']."￥",
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$user_info['balance']."￥",
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>$user_info['score']+$paylog_info['member_score'],
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>"会员充值须知：鼓励金是用作消费时抵部分现金使用，并已确认了附近有合作实体店铺，如果附近没有实体店可供您消费，请勿充值！",
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($user_info['openid'],config("tempids.glj_cz"),$data,config("WEB_DOMAIN")."index/member/glj.html");	
			}	
		}
	}
	
	//扫码付款
	function agent_pay_qrcode($paylog,$price,$pay_money,$agent_info,$user_info,$out_trade_no){
		$result = true;
		$rate_score 		= 0;
		$rate_member_score 	= 0;
		$rate_agent_score	= 0;
		$rate_commission	= 0;
		$payment_type		= 0;
		// 启动事务
		Db::startTrans();
		//付款金额1才可以赠送鼓励金
		$bijiao = bccomp(floatval($pay_money), floatval(1), 2);	
		//开启 鼓励金营销
		if($agent_info['is_score'] == 1 && $bijiao>=0){
			//全额付款(需送鼓励金)
			if(($price * 100) == ($pay_money * 100)){
				//判断商家是否赠送鼓励金
				if($agent_info['zs_score']>0){
					//商家送鼓励金比例
					$give_scale = bcdiv($agent_info['zs_score'], 100, 4);
					//计算送出鼓励金 = 付款金额 * 商家送鼓励金比例
					$give_score = bcmul($price, $give_scale, 4);
					//增加用户鼓励金
					$rest1 = db('info_user')->where('id', $user_info['id'])->setInc('score', $give_score);
					if(!$rest1) $result = false;
					
					//用户鼓励金记录
					$rest2 = $this->user_score_log($paylog['uid'],5,$give_score,"扫码消费".$price."元，送鼓励金".$give_score);
					if(!$rest2) $result = false;
					
					//减去商家鼓励金
					$rest3 = db('info_agent')->where('id', $agent_info['id'])->setDec('score', $give_score);
					if(!$rest3) $result = false;
					//商家鼓励金记录
					$rest4 = $this->agent_score_log($agent_info['id'],3,-$give_score,'用户'.$user_info['mobile'].'消费赠送鼓励金'.$give_score,$paylog['chain_id'],$paylog['clerk_id']);
					if(!$rest4) $result = false;
					
					//商家，用户鼓励金变化情况(便于统计)
					$rate_score 		= $give_score;
					$rate_member_score 	= $give_score;
					$rate_agent_score	= -$give_score;
					$payment_type		= 1;
				}
			}else{
				//判断商家是否抵扣鼓励金
				if($agent_info['ad_score']>0){
					//商家抵扣鼓励金比例
					$counteract = bcdiv($agent_info['ad_score'], 100, 4);
					//计算抵扣鼓励金 = 应付金额 * 商家抵扣比例
					$score_change = bcmul($paylog['origin_price'] , $counteract, 4);
					//商家，用户鼓励金变化情况(便于统计)
					db("log_paylog")
						->where('order_sn', $out_trade_no)
						->update(['score'=>$score_change,'member_score' =>-$score_change,'agent_score'=>$score_change,'payment_type'=>2]);
					
					//减用户鼓励金
					$rest7 = db('info_user')->where('id', $user_info['id'])->setDec('score', $score_change);
					if(!$rest7) $result = false;
					
					//用户鼓励金记录
					$rest8 = $this->user_score_log($paylog['uid'],5,-$score_change,"在商家".$agent_info['agent_name']."消费,抵扣鼓励金:".$score_change);
					if(!$rest8) $result = false;
					
					//加商家鼓励金
					$rest9 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_change);
					if(!$rest9) $result = false;
					
					//商家鼓励金记录
					$rest10 = $this->agent_score_log($agent_info['id'],3,$score_change,"收取用户".$user_info['mobile']."鼓励金抵扣:".$score_change,$paylog['chain_id'],$paylog['clerk_id']);
					if(!$rest10) $result = false;
					
					//商家，用户鼓励金变化情况(便于统计)
					$rate_score 		= $score_change;
					$rate_member_score 	= -$score_change;
					$rate_agent_score	= $score_change;
					$payment_type		= 2;
				}
			}
		}
		// 获取短信模板
		$template = db('sms_template') -> find(4);
		$msg['name'] = $price;
		//检查是否分店
		if($paylog['chain_id']>0){
			//获取收银员信息
			$employee_info = db('agent_clerk')->where('id',$paylog['clerk_id'])->find();
			//发送短信，提醒分店负责人
			$msg = send_sms($employee_info['mobile'], $template['tid'], json_encode($msg), $template['sign_name']);
		}else{
			//发送短信，提醒商家
			$msg = send_sms($agent_info['tel'], $template['tid'], json_encode($msg), $template['sign_name']);
		}
		if(config('open_sq') == 1 && $agent_info['is_union'] == 1){
			$rest11 = $this->ads_commission($paylog,$agent_info,$user_info);
			if(!$rest11) $result = false;
		}
		//费率分佣
		$new_rest = $this->feel_commission($paylog);
		if(!$new_rest)$result = false;
		
		//oem佣金费率
		$oem_feel = 0.001;
		//计算oem费率佣金
		$rate_commission 		= bcmul($paylog['balance'], $oem_feel, 4);
		
		//各级分佣统计
		$update['state'] 			= 2;
		$update['pay_time'] 		= now_time();
		$update['score'] 			= $rate_score;
		$update['member_score'] 	= $rate_member_score;
		$update['agent_score'] 		= $rate_agent_score;
		$update['payment_type'] 	= $payment_type;
		$update['rate_commission'] 	= $rate_commission;
	
		//更新订单信息 
		$rest12 = db('log_paylog')
					->where('order_sn',$paylog['order_sn'])
					->update($update);
					
		if(!$rest12) $result = false;
		
		if($result){
			//提交
			Db::commit();
		}else{
			//回滚
		    Db::rollback();
		    exit;
		}
		
		//获取日志
		$cut_paylog = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($cut_paylog['state'] == 2){
			//修改订单状态
			$this->add_corepaylog($cut_paylog);
			//发送用户付款通知
			if($user_info&&$user_info['openid']){
				$remark="付款成功";
				if($cut_paylog["member_score"]>0){
					$remark.=",鼓励金账号增加".$cut_paylog["member_score"];
				}elseif($cut_paylog["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$cut_paylog['member_score'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'付款成功通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$cut_paylog['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$agent_info['agent_name'],
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>$cut_paylog['order_sn'],
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($user_info['openid'],config("tempids.fk"),$data,config("WEB_DOMAIN")."index/member/index.html");	
			}
			//发送商户收款通知
			if($agent_info){
				$agent_user=db('info_user')->find($agent_info['user_id']);
				if(!$agent_user['openid']){
					return;
				}
				$remark="收款成功通知";
				if($cut_paylog["agent_score"]>0){
					$remark.=",用户抵扣回收鼓励金".$cut_paylog["agent_score"];
				}elseif($cut_paylog["agent_score"]<0){
					$remark.=",用户付款赠送鼓励金".$cut_paylog['agent_score'];
				}
				$chain_name=$agent_info['agent_name'];
				if($cut_paylog['chain_id']){
					$chain=db('agent_store')->field("store_name")->find($cut_paylog['chain_id']);
					$chain_name=$chain['store_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$chain_name,
	               	"color"=>"#173177"
				   ),
	            "keyword2"=>array(
	               	"value"=>$cut_paylog['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword3"=>array(
					"value"=>$cut_paylog['origin_price'],
					"color"=>"#173177"
				),
				"keyword4"=> array(
					"value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"                
				),
	            "keyword5"=> array(
	                "value"=>$cut_paylog['order_sn'],
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($agent_user['openid'],config("tempids.sk"),$data);	
			}
		}
		//app收款提醒
		push_msg($cut_paylog['agent_id'],$cut_paylog['balance']);
	}
	
	//商家充值广告费
	function agent_pay_ads($paylog,$agent_info,$config){
		
		$province_commission = 0;
		$city_commission	 = 0;
		$oem_commission		 = 0;
		$rate_commission	 = 0;
		
		//省代分佣比例
		$province_scale = $config['main_agency_commission']/100;
		$city_scale 	= $config['agency_commission']/100;
		$oem_scale 		= $config['platform_commission']/100;
		
		$result = true;
		// 启动事务
		Db::startTrans();
		//增加店铺广告余额
		$rest2 =db('info_agent')->where('id', $agent_info['id'])->setInc('ad_money', $paylog['balance']);
		if(!$rest2){
			$result = false;
		}
		//商家资金变化日志 
		$rest3 =$this->agent_money_log($paylog,7,$paylog['balance'],'广告费充值');
		if(!$rest3){
			$result = false;
		}
		//计算提前分佣金额
		$total_yongj = bcmul($paylog['balance'], 0.4, 4); 
		
		//省代佣金
		if($agent_info['agency_id1'] && $agent_info['agency_id1']>0){
			//计算省代佣金
			$province_yongj = bcmul($paylog['balance'], $province_scale, 4); 
			//省代佣金
			$province_commission = $province_yongj;
			//新增省代佣金
			$rest4 =db('info_oem')->where('id', $agent_info['agency_id1'])->setInc('commission', $province_yongj);
			if(!$rest4){
				$result = false;
			}
			//省代佣金记录 
			$rest5 =$this->oem_commission_log($agent_info['agency_id1'],3,$province_yongj,'商家'.$agent_info['agent_name'].'广告充值佣金');
			if(!$rest5){
				$result = false;
			}	
			//计算剩余佣金
			$total_yongj = bcsub($total_yongj, $province_yongj, 4);
		}
		//市代佣金
		if($agent_info['agency_id2'] && $agent_info['agency_id2']>0){
			//计算省代佣金
			$city_yongj = bcmul($paylog['balance'], $city_scale, 4); 
			//市代佣金
			$city_commission = $city_yongj;
			//新增市代佣金
			$rest6 =db('info_oem')->where('id', $agent_info['agency_id2'])->setInc('commission', $city_yongj);
			if(!$rest6){
				$result = false;
			}	
			//市代佣金记录 
			$rest7 =$this->oem_commission_log($agent_info['agency_id2'],3,$city_yongj,'商家'.$agent_info['agent_name'].'广告充值佣金');
			if(!$rest7){
				$result = false;
			}
			//计算剩余佣金
			$total_yongj = bcsub($total_yongj, $city_yongj, 4);
		}
		//oem佣金
		$oem_commission = $total_yongj;
		
		//新增oem佣金
		$rest8 =db('info_oem')->where('id', $agent_info['oem_id'])->setInc('commission', $total_yongj);
		if(!$rest8){
			$result = false;
		}
		//oem佣金记录
		$rest9 =$this->oem_commission_log($agent_info['oem_id'],3,$total_yongj,'商家'.$agent_info['agent_name'].'广告充值佣金');
	   	if(!$rest9){
			$result = false;
		}
		//新增广告费充值
		$rest10 = Db::table('sys_tongji')->where('id', 1)->setInc('ads_balances',$paylog['balance']);
		if(!$rest10)$result = false;
		
		
		//获取总账号信息
		$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
		//新增总账号余额
		$new_rest10 = Db::table('sys_tongji')->where('id', 1)->setInc('balances', $paylog['balance']);
		if(!$new_rest10) $result =false;
		
		
		//oem佣金费率
		$oem_feel = 0.001;
		
		//计算oem费率佣金
		$rate_commission 		= bcmul($paylog['balance'], $oem_feel, 4);
		
		//各级分佣统计
		$update['state'] 					= 2;
		$update['pay_time'] 				= now_time();
		$update['agency_id1_commission'] 	= $province_commission;
		$update['agency_id2_commission'] 	= $city_commission;
		$update['oem_commission'] 			= $oem_commission;
		$update['rate_commission'] 			= $rate_commission;
		
		//更新订单信息 
		$rest12 = db('log_paylog')
					->where('order_sn',$paylog['order_sn'])
					->update($update);
					
		if(!$rest12) $result = false;
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		
		if($paylog_info['state'] == 2) {
			$rest13 = $this->add_corepaylog($paylog_info);
			if(!$rest13) $result = false;
		}
		
		if($result){
			// 提交事务
		    Db::commit();
		}else{
			// 回滚事务
		    Db::rollback();
		    //$this->error('数据异常请联系管理员订单号：'.$paylog['order_sn']);
		}
	}
	
	//商家鼓励金充值
	function agent_pay_score($paylog,$agent_info){
		$result = true;
		// 启动事务
		Db::startTrans();
		//鼓励金变化值
		$score_charge = bcmul($paylog['balance'], 10, 2);
		//增加商家鼓励金
		$rest1 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_charge);
		if(!$rest1)$result = false;
		
		//商家鼓励金记录
		$rest2 = $this->agent_score_log($agent_info['id'],5,$score_charge,'鼓励金充值');
		if(!$rest2)$result = false;
		
		//获取总账号信息
		$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
		//计算当前总账号鼓励金
		$scores = $sys_tongji['scores'] + $score_charge;
		//计算当前总账号充值
		$balances = $sys_tongji['balances'] + $paylog['balance'];
		//更新总账号信息
		$rest10 = Db::table('sys_tongji')->where('id', 1)->update(['scores' => $scores,'balances'=>$balances]);
		if(!$rest10)$result = false;
		
		//更新订单信息 
		$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest12) $result = false;
		
		if($result){
			// 提交事务
		    Db::commit();    
		}else{
			// 回滚事务
		    Db::rollback();
			//print $e->getMessage();
		}
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
		}
	}
	
	//oem鼓励金充值
	function oem_pay_score($paylog){
		$result = true;
		// 启动事务
		Db::startTrans();
		//获取oem信息
		$oem_info = db('info_oem')->where('id',$paylog['uid'])->find();
		//鼓励金变化值
		$score_charge = bcmul($paylog['balance'], 10, 2);
		
		//增加oem鼓励金
		$rest1 = db('info_oem')->where('id', $oem_info['id'])->setInc('score', $score_charge);
		if(!$rest1)$result = false;
		
		//oem鼓励金记录
		$rest2 = $this->oem_score_log($oem_info['id'],5,$paylog['balance']*10,'鼓励金充值');
		if(!$rest2)$result = false;
		
		//获取总账号信息
		$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
		//计算当前总账号鼓励金
		$scores = $sys_tongji['scores'] + $score_charge;
		//计算当前总账号充值
		$balances = $sys_tongji['balances'] + $paylog['balance'];
		//更新总账号信息
		$rest10 = Db::table('sys_tongji')->where('id', 1)->update(['scores' => $scores,'balances'=>$balances]);
		if(!$rest10)$result = false;
		
		
		//更新订单信息 
		$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest12) $result = false;
		
		if($result){
			// 提交事务
		    Db::commit();    
			
		}else{
			// 回滚事务
		    Db::rollback();
			//print $e->getMessage();
		    //$this->error('数据异常请联系管理员订单号：'.$paylog['order_sn']);
		}
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
		}
		
	}
	
	
	//二维码收银
	function agent_sy_pay_qrcode($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no){
		$result = true;
		// 启动事务
		Db::startTrans();
		//付款金额1才可以赠送鼓励金
		$bijiao = bccomp(floatval($pay_money), floatval(1), 2);	
		//获取订单信息
		$sy_order_info = db('agent_syorder')->where('sn',$paylog['order_sn'])->find();
		if($sy_order_info['type']==5){
			$resh=db('agent_house')->where("id",$sy_order_info['house_id'])->update(["status"=>4,"finish_time"=>now_time()]);
			if(!$resh) $result = false;
		}
		//开启 鼓励金营销
		if($agent_info['is_score'] == 1 && $bijiao>=0){
			//全额付款(需送鼓励金)
			if(($price * 100) == ($pay_money * 100)){
				//判断该订单是否赠送鼓励金
				if(bccomp($sy_order_info['give_score'], 0.00, 2)>=0){
					//赠送鼓励金金额
					$rest1 = $give_score = $sy_order_info['give_score'];
					if(!$rest1) $result = false;
					
					//增加用户鼓励金
					$rest2 = db('info_user')->where('id', $user_info['id'])->setInc('score', $give_score);
					if(!$rest2) $result = false;
					
					//用户鼓励金记录  
					$rest3 = $this->user_score_log($user_info['id'],5,$give_score,"扫码消费".$price."元，送鼓励金".$give_score);
					if(!$rest3) $result = false;
					
					//减去商家鼓励金
					$rest4 = db('info_agent')->where('id', $agent_info['id'])->setDec('score', $give_score);
					if(!$rest4) $result = false;
					//商家鼓励金记录
					$rest5 = $this->agent_score_log($agent_info['id'],3,-$give_score,'用户'.$user_info['mobile'].'消费赠送鼓励金'.$give_score,$paylog['chain_id'],$paylog['clerk_id']);
					if(!$rest5) $result = false;
					
					//更新商家，用户鼓励金变化情况(便于统计)
					db("log_paylog")
					->where('order_sn', $out_trade_no)
					->update(['score'=>$give_score,'member_score' =>$give_score,'agent_score'=>-$give_score,'payment_type'=>1]);
				}
			}else{
				//判断当前订单是否抵扣鼓励金
				if(bccomp($sy_order_info['need_score'], 0.00, 2)>=0){
					//抵扣鼓励金金额
					$score_change = $sy_order_info['need_score'];
					//更新商家，用户鼓励金变化情况(便于统计)
					db("log_paylog")
					->where('order_sn', $out_trade_no)
					->update(['score'=>$score_change,'member_score' =>-$score_change,'agent_score'=>$score_change,'payment_type'=>2]);
					//减用户鼓励金
					$rest6 = db('info_user')->where('id', $user_info['id'])->setDec('score', $score_change);
					if(!$rest6) $result = false;
					
					//用户鼓励金记录	
					$rest7 = $this->user_score_log($user_info['id'],5,-$score_change,"在商家".$agent_info['agent_name']."消费,抵扣鼓励金:".$score_change);
					if(!$rest7) $result = false;
					
					//加商家鼓励金
					$rest8 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_change);
					if(!$rest8) $result = false;
					
					//商家鼓励金记录  
					$rest9 = $this->agent_score_log($agent_info['id'],3,$score_change,"收取用户".$user_info['mobile']."鼓励金抵扣:".$score_change,$paylog['chain_id'],$paylog['clerk_id']);
					if(!$rest9) $result = false;
				}
			}
		}
		// 获取短信模板
		$template = db('sms_template') -> find(4);
		$msg['name'] = $price;
		//检查是否分店
		if($paylog['chain_id']>0){
			//获取收银员信息
			$employee_info = db('agent_clerk')->where('id',$paylog['clerk_id'])->find();
			//发送短信，提醒分店负责人
			$msg = send_sms($employee_info['mobile'], $template['tid'], json_encode($msg), $template['sign_name']);
		}else{
			//发送短信，提醒商家
			$msg = send_sms($agent_info['tel'], $template['tid'], json_encode($msg), $template['sign_name']);
		}
		//获取订单信息
		$order_info = Db::table('agent_syorder')->where('sn',$out_trade_no)->find();
		//修改订单状态
		$rest14 = Db::table('agent_syorder')->where('sn',$out_trade_no)->update(['status' => 2]);
		if(!$rest14) $result = false;
		
		//获取订单详情
		$order_item_info = Db::table('agent_syorder_items')->where('order_id',$order_info['id'])->select();
			
		foreach($order_item_info as $key=>$value){
			//获取当前商品信息
			$goods_info = Db::table('agent_goods')->where('id', $value['goods_id'])->find();
			//计算剩余库存
			$goods_stock = $goods_info['stock'] - $value['num'];
			//计算累计销量
			$goods_sales = $goods_info['sales'] + $value['num'];
			//判断是否抵扣
			if(($paylog['balance'] * 100) == ($paylog['origin_price'] * 100)){
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['original_price'], $value['num']), 2);
				//累计赠送积分
				$total_give_score = bcadd($goods_info['total_give_score'], bcmul($goods_info['zs_price'], $value['num']), 2);
				//累计抵扣积分	
				$total_need_score = $goods_info['total_need_score'];
			}else{
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['sale_price'], $value['num']), 2);
				//累计赠送积分
				$total_give_score = $goods_info['total_give_score'];
				//累计抵扣积分	
				$total_need_score = bcadd($goods_info['total_need_score'], bcmul($goods_info['dk_price'], $value['num']), 2);
			}
				
			//减库存
			Db::table('agent_goods')
			->where('id', $value['goods_id'])
			->update(['stock' => $goods_stock,
						'sales'=>$goods_sales,
						'total_money'=>$total_money,
						'total_give_score'=>$total_give_score,
						'total_need_score'=> $total_need_score
						]);
		}
		//费率分佣
		$new_rest = $this->feel_commission($paylog);
		if(!$new_rest)$result = false;		
		
		
		//广告分佣
		if(config('open_sq') == 1 && $agent_info['is_union'] == 1){
			$rest11 = $this->ads_commission($paylog,$agent_info,$user_info);
			if(!$rest11) $result = false;
		}
		
		//更新订单信息 
		$rest19 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2]);
		if(!$rest19) $result = false;
		
		if($result){
			//提交
			Db::commit();
		}else{
		    //回滚
		    Db::rollback();
		    exit;
		}
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
		}
		//app收款提醒
		push_msg($paylog_info['agent_id'],$paylog_info['balance']);
		
	}
	
	//单产品二维码收银
	function goods_qrcode_pay($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no){
		$rate_score 		= 0;
		$rate_member_score	=0;
		$rate_agent_score	=0;
		$rate_payment_type	=0;
		
		$result = true;
		// 启动事务
		Db::startTrans();
		//付款金额1才可以赠送鼓励金
		$bijiao = bccomp(floatval($pay_money), floatval(1), 2);	
		//获取商品信息
		$goods_info = db('agent_goods')->where('id',$paylog['goods_id'])->find();
		//开启 鼓励金营销
		if($agent_info['is_score'] == 1 && $bijiao>=0){
			//全额付款(需送鼓励金)
			if(($price * 100) == ($pay_money * 100)){
				//判断商品是否赠送鼓励金
				if($goods_info['zs_price']>0){
					//计算赠送鼓励金 = 商品送鼓励金 * 商品数量
					$give_score = bcmul($goods_info['zs_price'], $paylog['goods_num'], 4);
					//增加用户鼓励金
					$rest1 = db('info_user')->where('id', $user_info['id'])->setInc('score', $give_score);
					if(!$rest1) $result =false; 
						
					//用户鼓励金记录	
					$rest2 = $this->user_score_log($user_info['id'],5,$give_score,"扫码消费".$price."元，送鼓励金".$give_score);
					if(!$rest2) $result =false; 
					
					//减去商家鼓励金
					$rest3 = db('info_agent')->where('id', $agent_info['id'])->setDec('score', $give_score);
					if(!$rest3) $result =false; 
					
					//商家鼓励金记录 	
					$rest4 = $this->agent_score_log($agent_info['id'],3,-$give_score,'用户'.$user_info['mobile'].'消费赠送鼓励金'.$give_score,$paylog['chain_id'],$paylog['clerk_id']);
					if(!$rest4) $result =false; 
					
					//更新商家，用户鼓励金变化情况(便于统计)
					$rate_score 		= $give_score;
					$rate_member_score	= $give_score;
					$rate_agent_score	= -$give_score;
					$rate_payment_type	= 1;
					
					}
				}else{
					//判断商家是否抵扣鼓励金
					if($goods_info['dk_price']>0){
						//计算抵扣鼓励金 = 商品抵扣金额 * 商品数量
						$score_change = bcmul($goods_info['dk_price'] , $paylog['goods_num'], 4);
						//商家，用户鼓励金变化情况(便于统计)
						$rate_score 		= $score_change;
						$rate_member_score	= -$score_change;
						$rate_agent_score	= $score_change;
						$rate_payment_type	= 2;
						
						//减用户鼓励金
						$rest7 = db('info_user')->where('id', $user_info['id'])->setDec('score', $score_change);
						if(!$rest7) $result =false; 
						
						//用户鼓励金记录	
						$rest8 = $this->user_score_log($user_info['id'],5,-$score_change,"在商家".$agent_info['agent_name']."消费,抵扣鼓励金:".$score_change);
						if(!$rest8) $result =false; 
						
						//加商家鼓励金
						$rest9 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_change);
						if(!$rest9) $result =false; 
						
						//商家鼓励金记录 	
						$rest10 = $this->agent_score_log($agent_info['id'],3,$score_change,"收取用户".$user_info['mobile']."鼓励金抵扣:".$score_change,$paylog['chain_id'],$paylog['clerk_id']);
						if(!$rest10) $result =false; 
					}
				}
			}
			
			// 获取短信模板
			$template = db('sms_template') -> find(4);
			$msg['name'] = $price;
			//检查是否分店
			if($paylog['chain_id']>0){
				//获取收银员信息
				$employee_info = db('agent_clerk')->where('id',$paylog['clerk_id'])->find();
				//发送短信，提醒分店负责人
				$msg = send_sms($employee_info['mobile'], $template['tid'], json_encode($msg), $template['sign_name']);
			}else{
				//发送短信，提醒商家
				$msg = send_sms($agent_info['tel'], $template['tid'], json_encode($msg), $template['sign_name']);
			}
			//获取当前商品信息
			$goods_info = Db::table('agent_goods')->where('id', $paylog['goods_id'])->find();
			//计算剩余库存
			$goods_stock = $goods_info['stock'] - $paylog['goods_num'];
			//计算累计销量
			$goods_sales = $goods_info['sales'] + $paylog['goods_num'];
			//判断是否抵扣
			if(($paylog['balance'] * 100) == ($paylog['origin_price'] * 100)){
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['original_price'], $paylog['goods_num']), 2);
				//累计赠送积分
				$total_give_score = bcadd($goods_info['total_give_score'], bcmul($goods_info['zs_price'], $paylog['goods_num']), 2);
				//累计抵扣积分	
				$total_need_score = $goods_info['total_need_score'];
			}else{
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['sale_price'], $paylog['goods_num']), 2);
				//累计赠送积分
				$total_give_score = $goods_info['total_give_score'];
				//累计抵扣积分	
				$total_need_score = bcadd($goods_info['total_need_score'], bcmul($goods_info['dk_price'], $paylog['goods_num']), 2);
			}
			
			//减库存
			$rest11 = Db::table('agent_goods')
						->where('id', $goods_info['id'])
						->update(['stock' => $goods_stock,
									'sales'=>$goods_sales,
									'total_money'=>$total_money,
									'total_give_score'=>$total_give_score,
									'total_need_score'=> $total_need_score
									]);
			if(!$rest11) $result =false;
			
			//oem费率佣金
			$rest13 = $this->feel_commission($paylog);
			if(!$rest13) $result =false;
			
			
			//广告分佣
			if(config('open_sq') == 1 && $agent_info['is_union'] == 1){
				$rest11 = $this->ads_commission($paylog,$agent_info,$user_info);
				if(!$rest11) $result = false;
			}
			
			
			//oem佣金费率
			$oem_feel = 0.001;
			
			//计算oem费率佣金
			$rate_commission 		= bcmul($paylog['balance'], $oem_feel, 4);
			
			//各级分佣统计
			$update['state'] 			= 2;
			$update['pay_time'] 		= now_time();
			$update['score'] 			= $rate_score;
			$update['member_score'] 	= $rate_member_score;
			$update['agent_score'] 		= $rate_agent_score;
			$update['payment_type'] 	= $rate_payment_type;
			$update['rate_commission'] 	= $rate_commission;
			
			
			//更新订单信息 
			$rest15 = db('log_paylog')
						->where('order_sn',$paylog['order_sn'])
						->update($update);
			if(!$rest15) $result = false;
			
			if($result){
				//提交
				Db::commit();
			}else{
				 //dump($e->getMessage());
			    //回滚
			    Db::rollback();
			    exit;
			}
			
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$this->add_corepaylog($paylog_info);
			//发送用户付款通知
			if($user_info&&$user_info['openid']){
				$remark="付款成功";
				if($paylog_info["member_score"]>0){
					$remark.=",鼓励金账号增加".$paylog_info["member_score"];
				}elseif($paylog_info["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$paylog_info['member_score'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'付款成功通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$agent_info['agent_name'],
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($user_info['openid'],config("tempids.fk"),$data,config("WEB_DOMAIN")."index/member/index.html");	
			}
			//发送商户收款通知
			if($agent_info){
				$agent_user=db('info_user')->find($agent_info['user_id']);
				if(!$agent_user['openid']){
					return;
				}
				$remark="收款成功通知";
				if($paylog_info["agent_score"]>0){
					$remark.=",用户抵扣回收鼓励金".$paylog_info["agent_score"];
				}elseif($paylog_info["agent_score"]<0){
					$remark.=",用户付款增送鼓励金".$paylog_info['agent_score'];
				}
				$chain_name=$agent_info['agent_name'];
				if($paylog_info['chain_id']){
					$chain=db('agent_store')->field("store_name")->find($paylog_info['chain_id']);
					$chain_name=$chain['store_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$chain_name,
	               	"color"=>"#173177"
				   ),
	            "keyword2"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword3"=>array(
					"value"=>$paylog_info['origin_price'],
					"color"=>"#173177"
				),
				"keyword4"=> array(
					"value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"                
				),
	            "keyword5"=> array(
	                "value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($agent_user['openid'],config("tempids.sk"),$data);	
			}
		}
		$prt=new Prt();	
		$prt->print_order3($paylog_info['id']);
		
		//app收款提醒
		push_msg($paylog_info['agent_id'],$paylog_info['balance']);
	}
	
	//用户商家关系
	function user_relevance_agent($u_id,$agent_id,$balance){
		
		$user_relevance_agent = db('user_relevance_agent')
								->where('user_id',$u_id)
								->where('agent_id',$agent_id)
								->find();
			if($user_relevance_agent){
				$relevance['total_money'] = bcadd($user_relevance_agent['total_money'], $balance, 2);
				$relevance['total_num'] = $user_relevance_agent['total_num']+1;
				return Db::table('user_relevance_agent')
						->where('id', $user_relevance_agent['id'])
						->update($relevance);
			}else{
				$relevance['user_id'] = $u_id;
				$relevance['agent_id'] = $agent_id;
				$relevance['total_money'] = $balance;
				$relevance['total_num'] = 1;
				
				return Db::table('user_relevance_agent')->insert($relevance);
			}
	}
	
	//费率分佣
	function feel_commission($paylog){
		$result = true;
		
		//oem佣金费率
		$pay_feel = config('pay_feel');
		//计算当前费率
		$oem_feel =  bcsub($pay_feel, 0.0025, 4);
		
		$oem_id = config('cut_oem_id');
		//计算oem费率佣金
		$oem_commission = bcmul($paylog['balance'], $oem_feel, 4);
		if($oem_commission>0){
			//更新oem佣金
			$resut1 = Db::table('info_oem')->where('id', $oem_id)->setInc('commission',$oem_commission);
			if(!$resut1) $result = false;
			
			//新增oem佣金记录
			$resut2 = $this->oem_commission_log($oem_id,7,$oem_commission,'商家收款费率：'.$oem_commission);
			if(!$resut2) $result = false;
		}
		
		
		return $result;
	}
	
	
	//广告分佣
	function ads_commission($paylog,$agent_info,$user_info){
		$result = true;
		//判断付款用户是否是自己的线下会员
		$cut_shou_user = db('info_user')->where('id',$agent_info['user_id'])->find();
		//开启云商圈
		if($user_info['level'] != $cut_shou_user['id']){
			//获取分佣
			$config=get_config("fx_config");	
			
			//单客次广告费
			$ad_one_money = $config['once_ads'];
			//联盟主广告佣金比例
			$union_main_scale = $config['union_main_commission']/100;
			//付款用户上级广告佣金比例
			$user_up_scale = $config['up_ads_commission']/100;
			//计算联盟主广告佣金40%,
			$union_main_adsmoney = bcmul($ad_one_money, $union_main_scale, 2);
			//计算付款用户上级广告佣金20%
			$user_up_adsmoney = bcmul($ad_one_money, $user_up_scale, 2);
			//查询商家已加入联盟 union_member
			$where['b.is_state'] = 1;	//联盟为正常状态
			$where['a.agent_id'] = $agent_info['id'];
			$where['a.state'] = 1;
	 		
	    	$list = db('union_member')
					->alias('a')
					->field('a.u_id as union_user_id ')
					->join('union_agent b','a.union_id = b.id')
					->where($where)
					->order('a.add_time desc')
					->select();
					
			//检查商家是否是联盟成员
			if(count($list)>0){
				//计算商家本次需支付联盟主广告费
				$union_main_all_adsmoney = bcmul(count($list), $union_main_adsmoney, 2);
				/***********计算商家本次一共需支付广告费********************/
				$config_scale =$config['agency_commission'] + $config['main_agency_commission']+$config['platform_commission'];
				
				$cut_money = bcmul($ad_one_money, $config_scale, 2);
				
				$total_adsmoney1 = bcadd($union_main_all_adsmoney, $user_up_adsmoney, 2);
				
				$total_adsmoney = bcadd($total_adsmoney1, $cut_money, 2);
				//当前店铺广告费余额大于本次广告费，广告费大于等于0.1元
				if(bccomp($agent_info['ad_money'], $total_adsmoney, 2)>=0 && $agent_info['is_union'] == 1){
					//减去商家广告费
					$rest1 = db('info_agent')->where('id', $agent_info['id'])->setDec('ad_money', $total_adsmoney);
					if(!$rest1) $result = false;
					//商家广告费日志 
					$rest2 = $this->agent_money_log($paylog,8,-$total_adsmoney,"支付广告费");
					if(!$rest2) $result = false;
					
					//增加付款用户上级佣金
					$rest3 = db('info_user')->where('id', $user_info['level'])->setInc('commission', $user_up_adsmoney);
					if(!$rest3) $result = false;
					//用户上级分佣日志
					$rest4 = $this->user_commission_log($user_info['level'],$paylog['order_sn'],3,$user_up_adsmoney,"收取推荐会员:".$user_info['mobile']."广告佣金",$paylog['pay_type']);
					if(!$rest4) $result = false;
					
					//检查用户是否加入联盟
					if(count($list)>0){
						//向联盟主支付广告费
						for($i=0;$i<count($list);$i++){
							//增加联盟主佣金
							$rest5 = db('info_user')->where('id', $list[$i]['union_user_id'])->setInc('commission', $union_main_adsmoney);
							if(!$rest5) $result = false;
							//联盟主分佣日志
							$rest6 = $this->user_commission_log($list[$i]['union_user_id'],$paylog['order_sn'],3,$union_main_adsmoney,"联盟成员:".$user_info['mobile']."广告佣金",$paylog['pay_type']);
							if(!$rest6) $result = false;
						}
					}else{
						//增加OEM广告费佣金
						$rest7 = db('info_oem')->where('id', $agent_info['oem_id'])->setInc('commission', $union_main_adsmoney);
						if(!$rest7) $result = false;
						
						//更新OEM佣金日志
						$rest8 = $this->oem_commission_log($agent_info['oem_id'],$agent_info['agency_id1'],$agent_info['agency_id2'],3,$union_main_adsmoney,"商家".$agent_info['agent_name']."鼓励金佣金");
						if(!$rest8) $result = false;
					}
				}else{
					//商家广告费不足，关闭商家云商圈
					$rest9 = db('info_agent')->where('id', $agent_info['id'])->update(['is_union' => 2]);
					if(!$rest9) $result = false;
				}
			}
		}
		return $result;
	}
	
	//商家申请开店
	function store_open($paylog,$config){
		//年费
		$annual_fee = $config['annual_fee'] ;
		//检查付款金额
		//if(bccomp($annual_fee, $paylog['balance']) == 0){
			//计算平台分佣
			$platform_openstore = bcmul($config['platform_openstore']/100, $annual_fee, 2);
			//计算省代分佣
			$main_agency_openstore = bcmul($config['main_agency_openstore']/100, $annual_fee, 2);
			//计算市代分佣
			$agency_openstore = bcmul($config['agency_openstore']/100, $annual_fee, 2);
			//计算商家分佣
			$up_agent_openstore = bcmul($config['up_agent_openstore']/100, $annual_fee, 2);
			//合伙人分佣
			$up_user_openstore = bcmul($config['up_user_openstore']/100, $annual_fee, 2);
			
			//获取用户信息
			$user_info = db('info_user')->where('id',$paylog['uid'])->find();
			//获取商家信息
			$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
			
			$result = true;
			// 启动事务
			Db::startTrans();
			//获取推荐用户信息
			$up_user = db('info_agent')->where('id',$user_info['tj_pt'])->find();
			//检查用户上级是否是合伙人
			if($up_user['is_pt'] == 1){
				//新增合伙人佣金
				$rest1 = db('info_user')->where('id', $user_info['tj_pt'])->setInc('commission', $up_user_openstore);
				if(!$rest1)$result =false;
				//合伙人佣金日志
				$rest2 = user_commission_log($user_info['tj_pt'],$paylog['order_sn'],7,$up_user_openstore,'下级会员'.$user_info['mobile'].'成功开店分佣');
				if(!$rest2)$result =false;
				
				//新增上级商家佣金
				$rest3 = db('info_agent')->where('id', $user_info['tj_agent'])->setInc('commission', $up_agent_openstore);
				if(!$rest3)$result =false;
				//商家佣金变化日志
				$rest4 = $this->agent_commission_log($user_info['tj_agent'],$paylog['order_sn'],7,$up_agent_openstore,'下级会员'.$user_info['mobile'].'成功开店分佣');
				if(!$rest4)$result =false;
				
				$update['pt_commission'] 			= $up_user_openstore;
				$update['tj_agent_commission'] 		= $up_agent_openstore;
				
			}else{
				//计算当前商家佣金
				$cut_agent_openstore = bcadd($up_agent_openstore, $up_user_openstore, 2);
				
				//新增上级商家佣金
				$rest5 = db('info_agent')->where('id', $user_info['tj_agent'])->setInc('commission', $cut_agent_openstore);
				if(!$rest5)$result =false;
				//商家佣金变化日志
				$rest6 = $this->agent_commission_log($user_info['tj_agent'],$paylog['order_sn'],7,$cut_agent_openstore,'下级会员'.$user_info['mobile'].'成功开店分佣');
				if(!$rest6)$result =false;
				
				$update['pt_commission'] 			= 0;
				$update['tj_agent_commission'] 		= $cut_agent_openstore;
			}
			
			//增加市代佣金
			$rest7 = db('info_oem')->where('id', $user_info['agency_id2'])->setInc('commission', $agency_openstore);
			if(!$rest7)$result =false;
			//市代佣金日志 
			$rest8 = $this->oem_commission_log($user_info['agency_id2'],10,$agency_openstore,'商家'.$agent_info['agent_name'].'申请开店佣金');
			if(!$rest8)$result =false;
			
			//增加省代佣金
			$rest9 = db('info_oem')->where('id', $user_info['agency_id1'])->setInc('commission', $main_agency_openstore);
			if(!$rest9)$result =false;
			//省代佣金日志
			$rest10 = $this->oem_commission_log($user_info['agency_id1'],10,$main_agency_openstore,'商家'.$agent_info['agent_name'].'申请开店佣金');
			if(!$rest10)$result =false;
			
			//增加平台佣金
			$rest11 = db('info_oem')->where('id', 1)->setInc('commission', $platform_openstore);
			if(!$rest11)$result =false;
			//平台佣金日志
			$rest12 = $this->oem_commission_log(1,10,$platform_openstore,'商家'.$agent_info['agent_name'].'申请开店佣金');
			if(!$rest12)$result =false;
			
			//获取总账号信息
			$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
			//新增总账号余额
			$new_rest10 = Db::table('sys_tongji')->where('id', 1)->setInc('balances', $paylog['balance']);
			if(!$new_rest10) $result =false;
			
			//各级分佣统计
			$update['state'] 					= 2;
			$update['pay_time'] 				= now_time();
			$update['oem_commission'] 			= $platform_openstore;
			$update['agency_id1_commission'] 	= $agency_openstore;
			$update['agency_id2_commission'] 	= $main_agency_openstore;
			$update['oem_id'] 					= 1;
			$update['agency_id1'] 				= $user_info['agency_id1'];
			$update['agency_id2'] 				= $user_info['agency_id2'];
			$update['pt_id'] 					= $user_info['tj_pt'];
			$update['tj_agent_id'] 				= $user_info['tj_agent'];
			
			//更新订单信息 
			$rest13 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update($update);
			if(!$rest13)$result =false;

			//更新商家信息
			$rest14 = db('info_agent')->where('id',$agent_info['id'])->update(['annual_fee' => 2]);
			if(!$rest14)$result =false;

			//获取订单信息
			$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
			if($paylog_info['state'] == 2) {
				$rest15 = $this->add_corepaylog($paylog_info);
			}
			
			if($result){
				//提交
				Db::commit();
			}else{
				 //dump($e->getMessage());
			    //回滚
			    Db::rollback();
			    exit;
			}
			
			
			
		//}
		
	}
    
}
